package com.cqie.secondhandtransaction.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cqie.secondhandtransaction.DTO.ChatInfoDTO;
import com.cqie.secondhandtransaction.DTO.UserDetailsDTO;
import com.cqie.secondhandtransaction.entity.ChatInfo;
import com.cqie.secondhandtransaction.entity.UserInfo;
import com.cqie.secondhandtransaction.exception.BusinessException;
import com.cqie.secondhandtransaction.handler.ChatHandler;
import com.cqie.secondhandtransaction.mapper.ChatInfoMapper;
import com.cqie.secondhandtransaction.mapper.UserInfoMapper;
import com.cqie.secondhandtransaction.service.ChatInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqie.secondhandtransaction.utils.WebSecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gdy
 * @since 2025-02-10
 */
@Service
public class ChatInfoServiceImpl extends ServiceImpl<ChatInfoMapper, ChatInfo> implements ChatInfoService {

    @Autowired
    private ChatInfoMapper chatInfoMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 保存消息
     *
     * @param chatInfo
     */
    @Override
    @Transactional
    public void saveMessage(ChatInfo chatInfo) {
        chatInfoMapper.insert(chatInfo);
    }

    /**
     * 消息记录
     *
     * @param chatCode
     * @return
     */
    @Override
    public List<ChatInfoDTO> getMessagesByChatCode(String chatCode) {
        QueryWrapper<ChatInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chat_code", chatCode);
        return chatInfoMapper.selectList(queryWrapper).stream()
                .filter(Objects::nonNull)
                .map(t -> {
                    ChatInfoDTO infoDTO = t.toChatInfoDTO();
                    infoDTO.setUsername(getUserNameById(t.getUserId()));
                    infoDTO.setSallerName(getUserNameById(t.getSallerId()));
                    return infoDTO;
                })
                .collect(Collectors.toList());
    }


    private String getUserNameById(Integer id) {
        UserInfo userInfo = userInfoMapper.selectById(id);
        if (Objects.isNull(userInfo)) {
            throw new BusinessException("用户未找到！");
        }
        return userInfo.getUserName();
    }
}
